package com.gwl.concurrent.exceptionhandler;

import static java.lang.System.out; 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class CaptureUncaughtException {

	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory()); 
		exec.execute(new ExceptionThread2()); 
	}

} 

class ExceptionThread2 implements Runnable {
	@Override
	public void run() {
		Thread t = Thread.currentThread(); 
		out.println("run by " + t); 
		out.println("UncaughtExceptionHandler: " + t.getUncaughtExceptionHandler()); 
		throw new RuntimeException(); 
	} 
} 
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
	@Override
	public void uncaughtException(Thread t, Throwable e) {
		out.println(t + " caught " + e); 
	} 
} 
class HandlerThreadFactory implements ThreadFactory {

	private MyUncaughtExceptionHandler exceptionHandler = new MyUncaughtExceptionHandler(); 
	
	@Override
	public Thread newThread(Runnable r) { 
		out.println(this + " create a thread"); 
		Thread t = new Thread(r); 
		t.setUncaughtExceptionHandler(exceptionHandler); 
		return t; 
	} 
}
